#!/usr/bin/env bash
#! Encoding UTF-8
PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
set -e

DOWNLOADER=
if [[ -z "${DOWNLOAD_BASE_PATH}" ]] ; then
    LOCAL_PATH=$(dirname $0)
    TMP_ROOT=${LOCAL_PATH}/tmp
else
    LOCAL_PATH=${DOWNLOAD_BASE_PATH}/geolite
    mkdir -p ${LOCAL_PATH}
    TMP_ROOT=${DOWNLOAD_BASE_PATH}/tmp
fi

# 需要设置，在官网取授权key
GEOIP_LICENSE_KEY="xxxxxxx"

info(){
    echo "$(date +'%F %T') [INFO] " "$@"
}
waring(){
    echo "$(date +'%F %T') [WARING] " "$@"
}
fatal(){
    echo "$(date +'%F %T') [ERROR] " "$@"
    exit 1
}

# --- create tempory directory and cleanup when done ---
setup_tmp() {
    TMP_DIR=$(mktemp -p ${TMP_ROOT} -d -t exporter-install.XXXXXXXXXX)
    cleanup() {
        code=$?
        set +e
        trap - EXIT
        rm -rf ${TMP_DIR}
        exit $code
    }
    trap cleanup INT EXIT
}

verify_downloader() {
    # Return failure if it doesn't exist or is no executable
    [ -x "$(which $1)" ] || return 1

    # Set verified executable as our downloader program and return success
    DOWNLOADER=$1
    return 0
}
# --- download from github url ---
download() {
    [ $# -eq 2 ] || fatal 'download needs exactly 2 arguments'

    case $DOWNLOADER in
        curl)
            if [[ -n ${PROXY_URL} ]] ; then
                curl -x ${PROXY_URL} -o $1 -sfL $2
            else
                curl -o $1 -sfL $2
            fi
            ;;
        wget)
            wget -qO $1 $2
            ;;
        *)
            fatal "Incorrect executable '$DOWNLOADER'"
            ;;
    esac

    # Abort if download command failed
    [ $? -eq 0 ] || waring 'Download failed'
}

main(){
    # openresty 下载
    verify_downloader curl \
        || verify_downloader wget \
        || fatal 'Can not find curl or wget for downloading files'
    setup_tmp

    mkdir -p ${LOCAL_PATH}
    for EDITION_ID in "GeoLite2-ASN" "GeoLite2-City" "GeoLite2-Country"; do
        # SHA256 URL
        HASH_URL="https://download.maxmind.com/app/geoip_download?edition_id=${EDITION_ID}&license_key=${GEOIP_LICENSE_KEY}&suffix=tar.gz.sha256"
        download ${TMP_DIR}/${EDITION_ID}_sha256sums ${HASH_URL}
        HASH_EXPECTED=$(grep " ${EDITION_ID}" ${TMP_DIR}/${EDITION_ID}_sha256sums | awk '{print $1}')
        if [[ -f ${LOCAL_PATH}/${EDITION_ID}.tar.gz ]] ; then
            HASH_INSTALLED=$(sha256sum ${LOCAL_PATH}/${EDITION_ID}.tar.gz | awk '{print $1}')
            if [ "${HASH_EXPECTED}" == "${HASH_INSTALLED}" ]; then
                waring "Promgram \"${EDITION_ID}.tar.gz\" already exists ."
                continue
            fi
        fi

        # Database URL
        DOWNLOAD_URL="https://download.maxmind.com/app/geoip_download?edition_id=${EDITION_ID}&license_key=${GEOIP_LICENSE_KEY}&suffix=tar.gz"
        download ${TMP_DIR}/${EDITION_ID}.tar.gz ${DOWNLOAD_URL}
        HASH_INSTALLED=$(sha256sum ${TMP_DIR}/${EDITION_ID}.tar.gz | awk '{print $1}')

        if [ "${HASH_EXPECTED}" == "${HASH_INSTALLED}" ]; then
            info "Promgram \"${EDITION_ID}.tar.gz\" download success ."
            cp -f ${TMP_DIR}/${EDITION_ID}.tar.gz ${LOCAL_PATH}/
        fi

    done

    for EDITION_ID in "GeoLite2-ASN-CSV" "GeoLite2-City-CSV" "GeoLite2-Country-CSV"; do
        # SHA256 URL
        HASH_URL="https://download.maxmind.com/app/geoip_download?edition_id=${EDITION_ID}&license_key=${GEOIP_LICENSE_KEY}&suffix=zip.sha256"
        download ${TMP_DIR}/${EDITION_ID}_sha256sums ${HASH_URL}
        HASH_EXPECTED=$(grep " ${EDITION_ID}" ${TMP_DIR}/${EDITION_ID}_sha256sums | awk '{print $1}')
        if [[ -f ${LOCAL_PATH}/${EDITION_ID}.zip ]] ; then
            HASH_INSTALLED=$(sha256sum ${LOCAL_PATH}/${EDITION_ID}.zip | awk '{print $1}')
            if [ "${HASH_EXPECTED}" == "${HASH_INSTALLED}" ]; then
                waring "Promgram \"${EDITION_ID}.zip\" already exists ."
                continue
            fi
        fi

        # Database URL
        DOWNLOAD_URL="https://download.maxmind.com/app/geoip_download?edition_id=${EDITION_ID}&license_key=${GEOIP_LICENSE_KEY}&suffix=zip"
        download ${TMP_DIR}/${EDITION_ID}.zip ${DOWNLOAD_URL}
        HASH_INSTALLED=$(sha256sum ${TMP_DIR}/${EDITION_ID}.zip | awk '{print $1}')

        if [ "${HASH_EXPECTED}" == "${HASH_INSTALLED}" ]; then
            info "Promgram \"${EDITION_ID}.zip\" download success ."
            cp -f ${TMP_DIR}/${EDITION_ID}.zip ${LOCAL_PATH}/
        fi

    done
}

main
